<template>
  <div class="app-container">
    <el-button
        type="primary"
        plain
        icon="Plus"
        @click="handleAdd"

    >新增</el-button>
    <el-tree
        v-loading="loading"
        :data="categoryList"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-expanded-keys="expandedKey"
        @check="currentChecked"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-link type="primary" :underline="false" @click="update(node, data)"> 编辑 </el-link>
            <el-link type="primary" :underline="false" v-if="node.level<=1" style="margin-left: 8px" @click="append(data)">新增</el-link>
            <el-link type="primary" :underline="false" v-if="node.childNodes.length===0" style="margin-left: 8px" @click="remove(node, data)"> 删除 </el-link>
          </span>
        </span>
      </template>
    </el-tree>

    <!-- 添加或修改产品类别对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类别名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/category";
import { getCurrentInstance,ref,reactive,toRefs } from 'vue';
import request from "@/utils/request";
import useStore from "@/store/index";
import {parseTime} from '@/utils/common'
import {ElMessage, ElMessageBox} from "element-plus";

const store=useStore().userStore.user
const { proxy } = getCurrentInstance();

const categoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 选中的节点
const selectedTree=ref({
  checkedKeys:[],
  checkedNodes:[]
});

// 默认展开的节点
const expandedKey=ref([]);

const defaultProps = {
  children: 'childrenList',
  label: 'name',
}

const currentChecked=(nodeObj, selectedObj)=>{
  // console.log(selectedObj)
  // 这是选中的节点的key数组
  // console.log(selectedObj.checkedKeys)
  // 这是选中的节点数组
  // console.log(selectedObj.checkedNodes)
  // console.log(selectedObj.checkedNodes.map(obj=>obj.name))
  selectedTree.value=selectedObj;
}

/**
 * 添加树节点
 * @param data
 */
const append = (data) => {
  let date=new Date();
  reset();
  open.value = true;
  title.value = "添加产品类别";
  form.value.parentId=data.id;
  form.value.sorted=0;
  form.value.delFlag=0;
  form.value.createBy=store.getUserId;
  form.value.updateBy=store.getUserId;
}

const update=(node, data)=>{
  reset();
  const _id = data.id || ids.value
  getCategory(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产品类别";
  });
}

/**
 * 移除树节点
 * @param node
 * @param data
 */
const remove = (node, data) => {
  // console.log('remove{node}:',node);
  // console.log('remove{data}:',data);
  // const _ids = selectedTree.value.checkedKeys;
  let _ids='';
  let name=''
  // 如果没有点击选择框，直接点击删除
  if(selectedTree.value.checkedKeys.length===0){
    _ids= data.id;
    name=data.name
  }else{
    _ids = selectedTree.value.checkedKeys;
    name=selectedTree.value.checkedNodes.map(obj=>obj.name);
  }
  ElMessageBox.confirm('是否确认删除产品类别名称为"' + name + '"的数据项？').then(function() {
    return delCategory(_ids);
  }).then(() => {
    getList();
    // 默认展开父节点
    expandedKey.value=[node.parent.data.id]
    // expandedKey.value=;
    ElMessage.success("删除成功");
  }).catch(() => {});
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: null,
    name: null,
    sorted: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品类别列表 */
function getList() {
  loading.value = true;
  listCategory(queryParams.value).then(response => {
    if(response.code==200){
      categoryList.value = response.data;
      total.value = response.data.length;
      loading.value = false;
    }else{
      ElMessage.error(`${response.msg}`);
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    parentId: null,
    name: null,
    sorted: null,
    createBy: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("categoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品类别";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCategory(_id).then(response => {
    if(response.code==200){
      form.value = response.data;
      open.value = true;
      title.value = "修改产品类别";
    }else{
      ElMessage.error(`${response.msg}`);
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      console.log('form:',form.value);
      if (form.value.id != null) {
        updateCategory(form.value).then(response => {
          if(response.code==200){
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          }else{
            ElMessage.error(`${response.msg}`);
          }
        });
      } else {
        addCategory(form.value).then(response => {
          if(response.code==200){
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          }else{
            ElMessage.error(`${response.msg}`);
          }
        });
      }
      expandedKey.value=[form.value.parentId];
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除产品类别编号为"' + _ids + '"的数据项？').then(function() {
    return delCategory(_ids);
  }).then((res) => {
    if(res.code===200){
      getList();
      ElMessage.success("删除成功");
    }else{
      ElMessage.error("删除失败");
    }
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/category/export', {
    ...queryParams.value
  }, `category_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>